package api

import (
	"log"

	"gitee.com/dingiyan/goMyAdmin/db"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type loginBody struct {
	// 使用email 作为userId进行登录
	Email    string `json:"email"`
	Password string `json:"password"`
}

// 登录接口
func Login(c *gin.Context) {
	body := &loginBody{}
	c.ShouldBindJSON(body)
	user, err := db.GetUserByEmail(body.Email)
	if err != nil {
		log.Println(err)
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  "login fail",
		})
		return
	}
	if user.Password != body.Password || user.IsStop {
		c.JSON(200, gin.H{
			"code": 2,
			"msg":  "login fail",
		})
		return
	}
	session := sessions.Default(c)
	session.Set("userId", user.ID)
	session.Set("userName", user.Name)
	session.Set("email", user.Email)
	session.Save()

	// 此处格式为前端所需
	c.JSON(200, success(gin.H{
		"userId": user.Email,
		"token":  "0",
		"roles":  []string{},
	}))
}

// 登出接口
func Logout(c *gin.Context) {
	session := sessions.Default(c)
	log.Printf("logout session id %v", session.ID())

	session.Clear()
	session.Save()

	// 上面的save将会保存一个空的session，但是还有cookie，所以手动设置cookie为空
	c.Writer.Header().Del("Set-Cookie")
	c.SetCookie("ginsession", "", -1, "/", "", false, true)

	c.JSON(200, success(true))
}
